package gzipTest

import (
	"bytes"
	"compress/gzip"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

type mybuf struct {
	buffer []byte
}

func (m *mybuf) Write(p []byte) (n int, err error) {
	m.buffer = append(m.buffer, p...)
	return
}

func TestOut() {
	buf := &mybuf{}
	str := `abcd`
	b := []byte(str)
	fmt.Println(len(b), "--->:", b)
	gz, err := gzip.NewWriterLevel(buf, gzip.DefaultCompression)
	if err != nil {
		fmt.Println(err)
		return
	}
	_, err = gz.Write(b)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = gz.Flush()
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(len(buf.buffer), buf.buffer)
	rdata := bytes.NewReader(buf.buffer)
	r, _ := gzip.NewReader(rdata)
	s, _ := ioutil.ReadAll(r)
	fmt.Println(string(s))
}

func Out1() {
	var b bytes.Buffer
	str := `abcd`
	gz := gzip.NewWriter(&b)
	if _, err := gz.Write([]byte(str)); err != nil {
		panic(err)
	}
	if err := gz.Flush(); err != nil {
		panic(err)
	}
	if err := gz.Close(); err != nil {
		panic(err)
	}
	fmt.Println(len(b.Bytes()), b.Bytes())
	fmt.Println(string(b.Bytes()))
	/*	str = base64.StdEncoding.EncodeToString(b.Bytes())
		fmt.Println(str)
		data, _ := base64.StdEncoding.DecodeString(str)
		fmt.Println(data)*/
	temp := []byte{1, 0, 0, 255, 255, 17, 205, 130, 237, 4, 0, 0, 0}
	rdata := bytes.NewReader(b.Bytes())
	r, _ := gzip.NewReader(rdata)
	s, _ := ioutil.ReadAll(r)
	fmt.Println(string(s))

	str = base64.StdEncoding.EncodeToString(temp)
	fmt.Println(str)
	str = base64.StdEncoding.EncodeToString(b.Bytes())
	fmt.Println(str)
	fmt.Println(string(temp))
}

func FileOut(fileName, extension string) {
	gzipFile := fileName + ".gzip"
	sourceFile := fileName + "." + extension
	file, err := os.Create(gzipFile)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	gz := gzip.NewWriter(file)
	defer gz.Close()

	reader, err := os.Open(sourceFile)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer reader.Close()
	gz.Header.Name = reader.Name()
	f, _ := reader.Stat()
	buf := make([]byte, f.Size())
	n, err := reader.Read(buf)
	if err != nil {
		fmt.Println(n)
		fmt.Println("read err :", err)
		return
	}
	n, err = gz.Write(buf)
	if err != nil {
		fmt.Println("gz write err ", err)
	}
	return
}

func GzipRead(fileName string) {
	fr, err := os.Open(fileName + ".gzip")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer fr.Close()

	gr, err := gzip.NewReader(fr)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer gr.Close()

	/*	buf := make([]byte, 1024*1024)
		n, err := gr.Read(buf)
		fmt.Println(n)*/
	str := strings.Split(gr.Header.Name, ".")

	var newName string
	for k, v := range str {
		if k == len(str)-1 {
			newName += "new." + v
			break
		}
		newName += v + "."
	}
	// 将包中的文件数据写入
	fw, err := os.Create(newName)
	if err != nil {
		fmt.Println(err)
		return
	}

	io.Copy(fw, gr)

	/*	n, err = fw.Write(buf)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(n)*/
}
